<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button v-allow="'import_employee'" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button v-allow="'export_employee'" type="danger" size="small" @click="hExportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 表格 -->
      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ setFormOfEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            background
            :current-page="pageParams.page"
            :page-sizes="[10, 20]"
            :page-size="pageParams.pagesize"
            :total="total"
            layout="total, sizes, prev,pager,next, jumper"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <EmpDialog
          v-if="showDialog"
          @close="hhClose"
          @updateEmpolyee="hUpdateEmpolyee"
        />
      </el-dialog>
      <el-dialog
        title="分配角色"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :visible.sync="showDialogRole"
      >
        <AssignRole
          v-if="showDialogRole"
          :id="curId"
          ref="refAssignRole"
          @close="showDialogRole=false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import Employees from '@/constant/employees'
import EmpDialog from './empDialog.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import AssignRole from './assignRole'
export default {
  components: {
    // eslint-disable-next-line vue/no-unused-components
    EmpDialog, AssignRole
  },
  data() {
    return {
      pageParams: {
        page: 1, // 查询第一页
        pagesize: 10 // 每页两条  --- 要与pagination中page-size一致
      },
      total: 0, // 总的数据条数
      list: [],
      showDialog: false,
      showDialogRole: false,
      curId: ''
    }
  },
  computed: {
    isLastPageFulled() {
      return this.total % this.pageParams.pagesize === 0
    },
    maxPage() {
      return Math.ceil(this.total / this.pageParams.pagesize)
    }
  },
  created() {
    this.loadEmployees()
    console.log(Employees.hireType, '枚举数据')
  },
  methods: {
    // 分页器点击事件
    hCurrentChange(curPage) {
    //   alert(curPage)
      // 1. 更新页码
      this.pageParams.page = curPage
      //   console.log(this.pageParams)
      // 2. 重发请求
      this.loadEmployees()
    },
    hSizeChange(curPageSize) {
    //   alert(curPageSize)
      // 1. 更改每页的条数
      this.pageParams.pagesize = curPageSize

      // 2. 重发请求
      this.loadEmployees()
    },
    // 获取员工数据
    async loadEmployees() {
      const res = await getEmployeeList(this.pageParams)
      console.log(res, '员工数据')
      this.list = res.data.rows
      this.total = res.data.total
    },
    setFormOfEmployment(id) {
      const obj = Employees.hireType.reduce((acc, cur) => {
        acc[cur.id] = cur.value
        return acc
      }, {})
      return obj[id]
    },
    // 删除功能
    async doDel(id) {
      // 1. 删除
      const res = await delEmployee(id)
      console.log('删除的结果', res)
      // 2. 提示
      this.$message.success('删除成功')

      if (this.list.length === 1) {
        this.pageParams.page--
        if (this.pageParams.page < 1) {
          this.pageParams.page = 1
        }
      }
      // 3. 重发请求
      this.loadEmployees()
    },
    hDel(id) {
      this.$confirm('确定要删除吗？', '友情提示').then(() => {
        this.doDel(id)
      }).catch(() => {

      })
    },
    hhClose() {
      this.showDialog = false
    },
    hUpdateEmpolyee() {
      // 1. 关闭弹层
      this.showDialog = false
      // 2. 更新表格数据
      // if(最后一页是满的){
      //   this.page = 最大页面 + 1
      // }
      // else (最后一页不是满) {
      //   // 最大页面的下一页
      //   this.page = 最后一页的页码
      // }
      // this.total : 一共几条 16
      // this.pageParams.pagesize: 每页显示几条 5
      if (this.total % this.pageParams.pagesize === 0) {
        this.pageParams.page = (this.total / this.pageParams.pagesize) + 1
      } else {
        // 最后一页的页码
        this.pageParams.page = Math.floor(this.total / this.pageParams.pagesize) + 1
      }
      this.loadEmployees()
    },
    formatDate(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log('做格式转换', rows)
      /** *
       * rows:
       * [
       *  {mobile:'13612345678', username:'管理员'.....}
       *  {mobile:'13612545678', username:'小王'.....}
       * ]
       *
       *
       *
       *  header:  [手机, 用户名]
       *  data: [ ['13612345678', '管理员'], ['13612545678', '小王'] ]
       */
      // 把英文的key转成中文的表头
      const enKeys = Object.keys(rows[0])

      const header = enKeys.map(enKey => map[enKey])

      const data = rows.map(obj => {
        return Object.values(obj)
      })
      console.log(enKeys, header, data)

      return {
        header,
        data // [ ['13612345678', '管理员'], [] ]
      }
    },
    // 导出
    async hExportExcel() {
      // 1. 求数据
      const res = await getEmployeeList(this.pageParams)
      console.log('员工信息是', res.data.rows)
      // 2. 做格式转换
      const { header, data } = this.formatDate(res.data.rows)
      console.log('结果', header, data)
      // 3. 调用Export2Excel保存数据到excel

      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '123', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },

    // 分配角色
    hAssignRole(id) {
    //   console.log('当前要分配角色id是', id)
      this.showDialogRole = true
      this.curId = id
    }
  }
}
</script>

<style lang="scss">
.page-tools {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .tips {
    line-height: 34px;
    padding: 0px 15px;
    border-radius: 5px;
    border: 1px solid rgba(145, 213, 255, 1);
    background: rgba(230, 247, 255, 1);
    i {
      margin-right: 10px;
      color: #409eff;
    }
  }
}
</style>
